package com.web.utils;

import com.domain.system.SysLog;
import com.domain.system.User;
import com.service.system.SysLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;

@Aspect     //声明切面类,需要配置 <aop:aspectj-autoproxy/>
@Component  //组件,被扫描
public class LogAspect {

    @Autowired
    private HttpSession session;
    @Autowired
    private SysLogService sysLogService;
    @Autowired
    private HttpServletRequest request;

    @Around("execution(* com.web.controller.*.*(..))")
    //不能确定代理类的返回值,所以用Object接收
    public Object log(ProceedingJoinPoint pjp) throws Throwable {
        //从session域中获取User
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser != null) {
            //必须用org.aspectj.lang.reflect下的 MethodSignature 接收,才可以调用方法
            MethodSignature methodSignature = (org.aspectj.lang.reflect.MethodSignature) pjp.getSignature();
            Method method = methodSignature.getMethod();
            RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);

            if (requestMapping!=null){
                //2、构造SysLog
                SysLog log = new SysLog();
                log.setTime(new Date());
                log.setUserName(loginUser.getUserName());
                log.setCompanyId(loginUser.getCompanyId());
                log.setCompanyName(loginUser.getCompanyName());
                //id在Service层设置了
//                log.setId(UUID.randomUUID().toString());
                log.setIp(request.getLocalAddr());//设置ip地址
                log.setMethod(method.getName());  //方法：list, toAdd, toUpdate, delete
                log.setAction(requestMapping.name());  //名称：RequestMapping.name();
                //3、写入数据库
                sysLogService.save(log);
            }

        }
        return pjp.proceed();
    }
}
